package com.whf.android.jar.web;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.webkit.WebView;


import androidx.annotation.Nullable;

import com.whf.android.jar.app.ConfigKeys;
import com.whf.android.jar.app.Latte;
import com.whf.android.jar.base.delegate.BaseDelegate;
import com.whf.android.jar.web.initializer.IWebViewInitializer;
import com.whf.android.jar.web.news.NewsWebView;
import com.whf.android.jar.web.route.RouteKeys;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;

/**
 * Created by 傅令杰
 */

public abstract class WebDelegate extends BaseDelegate implements IWebViewInitializer {

    private NewsWebView mWebView = null;
    private final ReferenceQueue<NewsWebView> WEB_VIEW_QUEUE = new ReferenceQueue<>();
    private String mUrl = null;
    private boolean handleWebUrl = true;
    /*** webView创建成功 */
    private boolean mIsWebViewAvailable = false;
    private BaseDelegate mTopDelegate = null;


    protected WebDelegate(String url, boolean handleWebUrl) {
        final Bundle args = new Bundle();
        args.putString(RouteKeys.URL.name(), url);
        args.putBoolean(RouteKeys.HANDLE_WEB_URL.name(), handleWebUrl);
        setArguments(args);
    }

    public abstract IWebViewInitializer setInitializer();

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final Bundle args = getArguments();
        if (args != null) {
            mUrl = args.getString(RouteKeys.URL.name());
            handleWebUrl = args.getBoolean(RouteKeys.HANDLE_WEB_URL.name(), true);
        }
        initWebView();
    }

    @SuppressLint("JavascriptInterface")
    private void initWebView() {
        if (mWebView != null) {
            //防止重复初始化与内存泄漏
            mWebView.removeAllViews();
            mWebView.destroy();
        } else {
            final IWebViewInitializer initializer = setInitializer();
            if (initializer != null) {
                //弱引用（new WebView 防止内存泄漏）
                final WeakReference<NewsWebView> webViewWeakReference =
                        new WeakReference<>(new NewsWebView(getContext()), WEB_VIEW_QUEUE);

                mWebView = webViewWeakReference.get();
                mWebView = initializer.initWebView(mWebView);
                mWebView.setWebViewClient(initializer.initWebViewClient());
                mWebView.setWebChromeClient(initializer.initWebChromeClient());
                //webView 中的下载事件
                mWebView.setDownloadListener(initializer.initDownloadListener());
                //webView 中的长按事件
                mWebView.setOnLongClickListener(initializer.initWebLongListener());
                //webView的原生与网页的交互
                final String javascript = Latte.getConfiguration(ConfigKeys.JAVASCRIPT_INTERFACE);
                mWebView.addJavascriptInterface(LatteWebInterface.create(this), javascript);
                mIsWebViewAvailable = true;
            } else {
                throw new NullPointerException("Initializer is null!");
            }
        }
    }

    /**
     * @param JavaScript:webView调用js的方法及传递参数
     */
    public void setJavaScript(String JavaScript) {
        if (mWebView != null) {
            mWebView.loadUrl("javascript:" + JavaScript);
        }
    }

    public void setTopDelegate(BaseDelegate delegate) {
        mTopDelegate = delegate;
    }

    public BaseDelegate getTopDelegate() {
        if (mTopDelegate == null) {
            mTopDelegate = this;
        }
        return mTopDelegate;
    }

    public WebView getWebView() {
        if (mWebView == null) {
            throw new NullPointerException("WebView IS NULL!");
        }
        return mIsWebViewAvailable ? mWebView : null;
    }

    public String getUrl() {
        if (mUrl == null) {
            throw new NullPointerException("WebView IS NULL!");
        }
        return mUrl;
    }

    public boolean isHandleWebUrl() {
        return handleWebUrl;
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mWebView != null) {
            mWebView.onPause();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mWebView != null) {
            mWebView.onResume();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mIsWebViewAvailable = false;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mWebView != null) {
            mWebView.clearHistory();
            mWebView.loadDataWithBaseURL(null, "",
                    "text/html", "utf-8", null);
            mWebView.loadUrl("about:blank");
            mWebView.stopLoading();
            mWebView.setWebChromeClient(null);
            mWebView.setWebViewClient(null);
            mWebView.removeAllViews();
            mWebView.destroy();
            mWebView = null;
        }
    }
}
